package com.cyd.springbootweb.sysThreadLocal;

import cn.hutool.core.util.StrUtil;
import com.cyd.springbootweb.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @version 1.0.0
 * Created by cyd on 2022-10-30 12:08:10
 * @ClassName : com.cyd.springbootweb.common.HttpRequestInterceptorSysThreadLocal
 * @Description : 拦截器，用于校验权限
 */
public class SysThreadLocalHttpRequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 校验用户
        String userId = request.getHeader("userId");
        if (StrUtil.isBlank(userId)) {
            throw new RuntimeException("用户未登录");
        }
        Integer threadLocalUserId = Integer.valueOf(userId);
        User threadLocalUser = this.queryUser(threadLocalUserId);
        if (Objects.isNull(threadLocalUser)) {
            throw new RuntimeException("检测到非法用户登录");
        }

        // 将用户放入线程上下文
        SysThreadLocal.setUser(threadLocalUser);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }


    /**
     * 注意：请求结束一定要清空上下文
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        SysThreadLocal.clear();
    }

    /**
     * 模拟从数据库获取User
     */
    private User queryUser(Integer userId) {
        User user = new User().setUserId(1).setAge(10).setName("mike");
        if (userId.equals(user.getUserId())) {
            return user;
        } else {
            return null;
        }
    }
}
